function [ U,tag_seq,labels ] = calc_u( g )
    U = zeros(size(g,3),2);
    tag_seq = zeros(size(g,3),2);
    labels = zeros(size(g,3),1);
    
    % forward
    % base case
    for k = 1:size(g,3)
        if (k == 1)
            % U(k,v) = max(u) g(u,v,k)
            [U(k,1), tag_seq(k,1)] = max([g(1,1,k) g(2,1,k)]);
            [U(k,2), tag_seq(k,2)] = max([g(1,2,k) g(2,2,k)]);
        else
            [U(k,1), tag_seq(k,1)] = max([U(k-1,1)+g(1,1,k) U(k-1,2)+g(2,1,k)]);
            [U(k,2), tag_seq(k,2)] = max([U(k-1,1)+g(1,2,k) U(k-1,2)+g(2,2,k)]);
        end
    end
    
    % backward
    labels(size(g,3)) = 2;

    for i = size(g,3)-1:-1:1
        labels(i) = tag_seq(i,labels(i+1));
    end
    
%     for v = 1:2
%         U(1,v) = max([g(1,v,1) g(2,v,1)]);
%     end
% 
%     for k = 2:size(g,3)
%         for v = 1:2
%             U(k,v) = max(U(k-1,:)' + g(:,v,k));
%         end
%     end
%     
%     labels(k) = 2;
%     for k = (size(g,3)-1):-1:1
%         [~,in] = max(U(k,:));
%         labels(k) = in;
%     end
    
end